#!/usr/bin/env bash
export DEBIAN_FRONTEND=noninteractive

# DBNAME=newbranchdb
# DBUSER=newbranch
# DBPASSWD=pliV1Cew

sudo aptitude update -q

sudo apt-get install -y build-essential tcl8.5

# Force a blank root password for mysql
# echo "mysql-server mysql-server/root_password password " | debconf-set-selections
# echo "mysql-server mysql-server/root_password_again password " | debconf-set-selections

# Install mysql, nginx, php5-fpm
sudo aptitude install -q -y -f nginx php5-fpm php5-dev

# Install commonly used php packages
sudo aptitude install -q -y -f php5-mysql php5-curl php5-gd php5-intl php-pear php5-imagick php5-imap php5-mcrypt php5-memcached php5-ming php5-ps php5-pspell php5-recode php5-snmp php5-sqlite php5-tidy php5-xmlrpc php5-xsl php5-xcache

sudo rm /etc/nginx/sites-available/default
sudo touch /etc/nginx/sites-available/default

sudo cat >> /etc/nginx/sites-available/default <<'EOF'
server {
  listen   80;

  root /usr/share/nginx/html;
  index index.php index.html index.htm;

  Make site accessible from http://localhost/
  server_name _;

  location / {
    # First attempt to serve request as file, then
    # as directory, then fall back to index.html
    try_files $uri $uri/ /index.html;
	   #proxy_set_header X-Real-Ip $remote_addr;
	   #proxy_set_header Host $http_host;
	   #proxy_pass	 http://127.0.0.1:2368;
  }

  location /doc/ {
    alias /usr/share/doc/;
    autoindex on;
    allow 127.0.0.1;
    deny all;
  }

  # redirect server error pages to the static page /50x.html
  #
  error_page 500 502 503 504 /50x.html;
  location = /50x.html {
    root /usr/share/nginx/html;
  }

  # pass the PHP scripts to FastCGI server listening on /tmp/php5-fpm.sock
  #
  location ~ \.php$ {
    try_files $uri =404;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
  }

  # deny access to .htaccess files, if Apache's document root
  # concurs with nginx's one
  #
  location ~ /\.ht {
    deny all;
  }

  ### phpMyAdmin ###
  location /phpmyadmin {
    root /usr/share/;
    index index.php index.html index.htm;
    location ~ ^/phpmyadmin/(.+\.php)$ {
      client_max_body_size 4M;
      client_body_buffer_size 128k;
      try_files $uri =404;
      root /usr/share/;

      # Point it to the fpm socket;
      fastcgi_pass unix:/var/run/php5-fpm.sock;
      fastcgi_index index.php;
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      include /etc/nginx/fastcgi_params;
    }

    location ~* ^/phpmyadmin/(.+\.(jpg|jpeg|gif|css|png|js|ico|html|xml|txt)) {
      root /usr/share/;
    }
  }
  location /phpMyAdmin {
    rewrite ^/* /phpmyadmin last;
  }
  ### phpMyAdmin ###
}
EOF

# create virtual host

sudo touch /etc/nginx/sites-available/site.config

sudo cat >> /etc/nginx/sites-available/site.config <<'EOF'

    upstream app_gck_io {
      server 127.0.0.1:3001;
    }

    # the nginx server instance
    server {
      listen 80;
      server_name gck.local;
      access_log /var/log/gck.access.log;
      error_log /var/log/gck.error.log;

      # pass the request to the node.js server with the correct headers and much more can be added, see nginx config options
      location / {
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header Host $http_host;
          proxy_set_header X-NginX-Proxy true;

          proxy_pass http://app_gck_io/;
          proxy_redirect off;

         # let it serve off the websocket alas socket.io
          proxy_http_version 1.1;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection "upgrade";
      }
    }

EOF

sudo ln -s /etc/nginx/sites-available/site.config /etc/nginx/sites-enabled/gck.io

echo -e 'nginx setup completed, now start upstart for nodejs app\n\n'

# in fact just run this is enough
wget -nv bit.ly/iojs-dev -O /tmp/iojs-dev.sh; bash /tmp/iojs-dev.sh

#sudo aptitude install -q -y -f nodejs

#sudo aptitude install -q -y -f npm

#sudo ln -s /usr/bin/nodejs /usr/bin/node

sudo aptitude install -q -y -f install upstart

sudo touch /etc/init/gckapp.conf

sudo cat >> /etc/init/gckapp.conf <<'EOF'

#!upstart

    description "gck.io MEAN stack"
    author "Joel Chu"

    env LOG_FILE=/var/log/node/gck.log
    env APP_DIR=/var/www
    env APP=server.js
    env PID_NAME=gckapp.pid
    env USER=www-data
    env GROUP=www-data
    env POST_START_MESSAGE_TO_LOG="gck.io has started"
    env NODE_BIN=/usr/bin/node
    env PID_PATH=/var/opt/node/run
    env SERVER_ENV="production"
    env PORT=3001

    ######################################################

    start on (local-filesystems and net-device-up IFACE=eth0)
    stop on shutdown

    respawn
    respawn limit 99 5

    pre-start script
        mkdir -p $PID_PATH
        mkdir -p /var/log/node
    end script

    script
        export NODE_ENV=$SERVER_ENV
        exec start-stop-daemon --start --chuid $USER:$GROUP --make-pidfile --pidfile $PID_PATH/$PID_NAME --chdir $APP_DIR --exec $NODE_BIN -- $APP >> $LOG_FILE 2>&1
    end script

    post-start script
        echo $POST_START_MESSAGE_TO_LOG >> $LOG_FILE
    end script

EOF

# don't know why it installed apache2 just remove it here

# sudo apt-get -y remove apache2

# remove the default configuration file

sudo rm /etc/nginx/sites-enabled/default

sudo service nginx restart

sudo service php5-fpm restart

# try to use io.js so not going to install nodejs here

echo -e "Install webmin"

cat >>/etc/apt/sources.list <<EOF

#add webmin source

deb http://download.webmin.com/download/repository sarge contrib
deb http://webmin.mirror.somersettechsolutions.co.uk/repository sarge contrib

EOF

sudo wget http://www.webmin.com/jcameron-key.asc

sudo apt-key add jcameron-key.asc

sudo apt-get update

sudo aptitude install -q -y -f install webmin

echo -e "\n\n--- INSTALL MONGO --\n\n";

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list

sudo apt-get update

sudo apt-get install -y mongodb-org

# setup a data folder for mongo

sudo mkdir -p /data/db

echo "If you need to allow mongodb connection from outside of the virtual box, you must edit the /etc/mongod.conf see /vagrant/README.md for more details\r\n";

# installing couchDB

sudo apt-get install couchdb -y



echo -e "\n\n--- Done! Bye! ---\n\n"
